<script setup lang="ts">
import LineChart from './components/line-chart/index.vue'
import { Edit } from '@element-plus/icons-vue'
import { carbonAssetsApi } from '@/api'
import type { CarbonAssetsInfo } from '@/types'

const tanpanchaStore = useTanpanchaStore()
const protocol = ref(tanpanchaStore.standards[0]?.value)
const year = ref(`${new Date().getFullYear()}`)
const point = ref()
const loading = ref(false)
const info = shallowRef({} as CarbonAssetsInfo)
async function handleClickNode(node: any) {
  point.value = node.id
  await nextTick()
  if (!protocol.value) {
    setTimeout(() => {
      getInfo()
    }, 20)
  }
  else {
    getInfo()
  }
}
async function getInfo() {
  if (!unref(point) || !unref(year) || !unref(protocol))
    return
  loading.value = true
  try {
    const { data } = await carbonAssetsApi.queryCarbonAssets({
      pointId: unref(point),
      dataTime: +unref(year),
      protocolCode: unref(protocol),
    })
    info.value = data
  }
  finally {
    loading.value = false
  }
}

async function editCCER() {
  ElMessageBox.prompt('请输入CCER总量', '提示', {
    inputValue: `${unref(info).ccerNum ?? 0}`,
    inputPattern: /^\d+(\.\d+)?$/,
    inputErrorMessage: '请输入数字',
  }).then(async ({ value }) => {
    await carbonAssetsApi.saveCcerNum({
      dataTime: +unref(year),
      ccerNum: +value,
    })
    ElMessage.success('CCER更新成功')
    getInfo()
  }).catch(() => {})
}
async function clickSearch() {
  await getInfo()
}

watch(() => tanpanchaStore.standards, () => {
  protocol.value = tanpanchaStore.standards[0]?.value
})

watch(protocol, async () => {
  getInfo()
})
</script>

<template>
  <div class="padding-sm flex container">
    <ReadonlyPointTree
      fire
      class="flex-incompressible"
      @click-node="handleClickNode"
    />
    <div class="ml-4 flex flex-auto flex-col">
      <ElForm inline>
        <ElFormItem label="核算年份">
          <ElDatePicker
            v-model="year"
            type="year"
            :editable="false"
            :clearable="false"
            placeholder="选择年份"
            value-format="YYYY"
            format="YYYY"
          />
        </ElFormItem>
        <ElFormItem label="核算标准">
          <ElSelect v-model="protocol" class="free !w-50" :clearable="false">
            <ElOption v-for="item in tanpanchaStore.standards" :key="item.value" :label="item.name" :value="item.value" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <SearchButton @click="clickSearch" />
        </ElFormItem>
      </ElForm>
      <div class="flex flex-shrink-0 items-center gap-4">
        <div class="alpha-block flex-auto py-3">
          <div class="p-3 opacity-80">
            碳配额总量（{{ tanpanchaStore.panchaUnit }}）
          </div>
          <p class="fs-24 my-0 p-3">
            {{ info.quotaNum ?? '-' }}
          </p>
        </div>
        <div class="alpha-block flex-auto py-3">
          <div class="p-3 opacity-80">
            CCER总量（{{ tanpanchaStore.panchaUnit }}）
          </div>
          <p class="fs-24 my-0 p-3">
            {{ info.ccerNum ?? '-' }}
            <ElIcon class="ml-2 cursor-pointer" :size="20" @click="editCCER">
              <Edit />
            </ElIcon>
          </p>
        </div>
        <div class="alpha-block flex-auto py-3">
          <div class="p-3 opacity-80">
            年度排放量（{{ tanpanchaStore.panchaUnit }}）
          </div>
          <p class="fs-24 my-0 p-3">
            {{ info.emissionNum ?? '-' }}
          </p>
        </div>
        <div class="alpha-block flex-auto py-3">
          <div class="p-3 opacity-80">
            剩余排放量（{{ tanpanchaStore.panchaUnit }}）
          </div>
          <p class="fs-24 my-0 p-3">
            {{ info.residueNum ?? '-' }}
          </p>
        </div>
      </div>
      <div class="alpha-block mt-4 flex-auto overflow-auto">
        <LineChart :data="info.emissionList ?? []" :base-line-value="info.quotaBaseLine ?? 0" />
      </div>
    </div>
  </div>
</template>
